package com.xiaren.biz;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.JOptionPane;

import com.xiaren.common.IConstant;
import com.xiaren.common.ObjectConstant;
import com.xiaren.ui.edit.FileEdit;
import com.xiaren.ui.tree.JTreeBiz;
import com.xiaren.util.SystemTrayUtil;

/**
 * @主页 http://www.leaf123.cn/
 * @邮箱 xia5523@qq.com
 */
public class PublicFunction {


	/**
	 * 判断是否有文件没有保存
	 *
	 * @return 返回true，代表有文件没有保存
	 */
	public static boolean fileNotSave() {
		for (int i = 0; i < ObjectConstant.mainEdit.getTabCount(); i++) {
			FileEdit edit = (FileEdit) ObjectConstant.mainEdit.getComponent(i);
			if (!edit.isSave) {// 只要有一个没保存
				return true;
			}
		}
		return false;
	}

	/**
	 * 保存所有文件操作
	 */
	public static void saveAllFile() {
		for (int i = 0; i < ObjectConstant.mainEdit.getTabCount(); i++) {
			FileEdit edit = (FileEdit) ObjectConstant.mainEdit.getComponent(i);
			if (!edit.isSave) {// 如果没有保存，则保存
				edit.saveMySelf();
			}
		}
	}

	/**
	 * 关闭程序操作<br/>
	 * 关闭窗体前判断是否需要保存
	 */
	public static void exitSys() {
		if (fileNotSave()) {
			int result = JOptionPane.showConfirmDialog(ObjectConstant.mainFrame,
					"Some file without saving, needs to be saved ?", "close System", JOptionPane.YES_NO_CANCEL_OPTION);
			if (result == JOptionPane.OK_OPTION) {
				saveAllFile();
			} else if (result == JOptionPane.OK_CANCEL_OPTION) {
				return;
			}
		}
		IConstant.setProperties(IConstant.LOCALX,
				ObjectConstant.mainFrame.getLocation().x + "");
		IConstant.setProperties(IConstant.LOCALY,
				ObjectConstant.mainFrame.getLocation().y + "");
		IConstant.setProperties(IConstant.WIDTH,
				ObjectConstant.mainFrame.getWidth() + "");
		IConstant.setProperties(IConstant.HEIGHT,
				ObjectConstant.mainFrame.getHeight() + "");


		System.exit(0);
	}

	/**
	 * 关闭程序操作<br/>
	 * 直接关闭窗体
	 */
	public static void exitSysAbs() {
		IConstant.setProperties(IConstant.LOCALX,
				ObjectConstant.mainFrame.getLocation().x + "");
		IConstant.setProperties(IConstant.LOCALY,
				ObjectConstant.mainFrame.getLocation().y + "");
		IConstant.setProperties(IConstant.WIDTH,
				ObjectConstant.mainFrame.getWidth() + "");
		IConstant.setProperties(IConstant.HEIGHT,
				ObjectConstant.mainFrame.getHeight() + "");
		SystemTrayUtil.tray.remove(SystemTrayUtil.trayIcon);//用于移除托盘图标（目前尚未测试，是否正的有用）
		System.exit(0);
	}

	public static void help(){
		System.out.println("hel");
		ObjectConstant.treeBiz.noteToList(ObjectConstant.treeBiz.rootNote);
		ObjectConstant.mainTree.updateUI();
	}
	/**
	 * 运行传入多来的内容，用cmd运行
	 * @param cmdarray
	 * @throws IOException
	 */
	public static void runCmdProgress(String... cmdarray) throws IOException{
		Runtime rt = Runtime.getRuntime();
		for (String runCmd : cmdarray) {
			rt.exec("cmd /c start " + runCmd);
		}
	}


}
